import { Component, OnInit, Input, EventEmitter, Output, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { DatePipe } from '@angular/common';
import { StatusFollowService } from '@core/statusFollow.service';
import { NzMessageService, NzTreeSelectComponent } from 'ng-zorro-antd';
import { ApiService } from '@core/api.service';
import { LocalStorage } from '@core/local.storage';
@Component({
    selector: 'app-zdrwgzqd-editor',
    templateUrl: './zdrwgzqd_editor.component.html',
    styleUrls: ['./zdrwgzqd_editor.component.less']
})

export class ZdrwgzqdEditorComponent implements OnInit {
    mode = '';
    gzxmList = [];
    qtbmNodes = [];
    phbmNodes = [];
    @ViewChild('qtbmTree', { static: false }) qtbmTree: NzTreeSelectComponent;
    @ViewChild('phbmTree', { static: false }) phbmTree: NzTreeSelectComponent;
    @Output() optSuccess = new EventEmitter();
    @Output() optCancel = new EventEmitter();

    @Input() set params(param) {
        if (!param.mode) {
            return;
        }
        this.mode = param.mode;
        if (param.mode === 'edit') {
            this.initSaveParam(param.row);
        } else {
            this.saveParam = {};
        }
        this.gzxmList = param.gzxmList || [];
        this.qtbmNodes = param.qtbmNodes || [];
        this.phbmNodes = param.phbmNodes || [];
    };
    saveParam: any = {};
    userInfo = JSON.parse(this.ls.get('loginInfo'));
    phbmList = [];
    constructor(
        private http: _HttpClient,
        private datePipe: DatePipe,
        public statusFollowService: StatusFollowService,
        public message: NzMessageService,
        public apiService: ApiService,
        private ls: LocalStorage,
    ) { }

    ngOnInit() {

    }

    initSaveParam(row) {
        this.saveParam = {};
        if (row.year) {
            row._year = new Date(row.year);
        }
        if (row.limitDate) {
            row._limitDate = new Date(row.limitDate);
        }
        if (row.assistPartId) {
            row._assistPartIds = row.assistPartId.split(',');
        }
        Object.assign(this.saveParam, row);
    }

    /**
     * 删除私立字段
     * @param param 1
     */
    removePrivateFields(param) {
        Object.keys(param).forEach(key => {
            if (key.indexOf('_') !== -1 || param[key] === null || param[key] === undefined) {
                delete param[key];
            }
        });
    }

    /**
     * 删除后台不接受的字段
     * @param param 1
     */
    removeUnacceptableFields(param) {
        Object.keys(param).forEach(key => {
            switch (key) {
                case 'checked':
                case 'sysDel':
                case 'sysDate':
                case 'sysUser':
                case 'status':
                    delete param[key];
                    break;
                default:
                    break;
            }
        });
    }

    getGzxmName(projectId) {
        for (const el of this.gzxmList) {
            if (el.vcDictCode === projectId) {
                return el.vcDictName;
            }
        }
    }


    beforeSave(row) {
        if (row._year) {
            row.year = this.datePipe.transform(row._year, 'yyyy');
        }
        if (row._limitDate) {
            row.limitDate = this.datePipe.transform(row._limitDate, 'yyyy-MM-dd');
        }
        if (this.mode === 'add') {
            row.leadPartId = this.userInfo.VC_ORG$ID;
            row.leadPart = this.userInfo.VC_ORG$NAME;
        }
        if (row._assistPartIds.length && this.phbmNodes.length) {
            row.assistPartId = row._assistPartIds.join();
            const _assistPartNames = [];
            row._assistPartIds.forEach(id => {
                _assistPartNames.push(this.phbmTree.getTreeNodeByKey(id).title);
            });
            row.assistPart = _assistPartNames.join('、');
        } else {
            row.assistPart = '';
            row.assistPartId = '';
        }

        if (row.projectId) {
            row.project = this.getGzxmName(row.projectId);
        }
        this.removeUnacceptableFields(row);
        this.removePrivateFields(row);
    }


    save() {
        const param = {};
        Object.assign(param, this.saveParam);
        this.beforeSave(param);
        const ob: any = {
            'add': this.add(param),
            'edit': this.update(param),
        }
        ob[this.mode].subscribe(res => {
            if (res.msg === 'Ok') {
                this.message.success('保存成功');
                this.optSuccess.emit();
                this.cancel();
            } else {
                this.message.success('保存失败');
            }
        })
    }

    cancel() {
        this.optCancel.emit();
    }



    /**
     * 新增
     * @param project 工作项目
     * @param projectId 工作项目
     * @param entryPoint 项点
     * @param taskRequirements 落实要求
     * @param leadPartId 牵头部门编号
     * @param assistPartI 配合部门编号
     * @param leadPart 牵头部门
     * @param assistPart 配合部门
     * @param limitDate 完成时限
     * @param headLeader 督办领导
     * @param segCharger 科室负责人
     * @param status 状态
     * @param sysUser 录入人
     * @param sysDat 录入时间
     * @param year 年份
     */
    add(param) {
        const dataurl = environment.problem + '/keyTask/add';
        return this.http.post(dataurl, param);
    }

    /**
     * 修改
     * @param id 1
     * @param project 工作项目
     * @param projectId 工作项目
     * @param entryPoint 项点
     * @param taskRequirements 落实要求
     * @param leadPart 牵头部门
     * @param assistPart 配合部门
     * @param limitDate 完成时限
     * @param headLeader 督办领导
     * @param segCharger 科室负责人
     * @param status 状态
     * @param sysUser 录入人
     * @param sysDat 录入时间
     * @param year 年份
     * @param leadPartId 牵头部门编号
     * @param assistPartI 配合部门编号
     */
    update(param) {
        const dataurl = environment.problem + '/keyTask/update';
        return this.http.post(dataurl, param);
    }
    /**
     * 作业
     * stationName=珠琳
     * devName=
     */
    getZymList(param) {
        const dataurl = environment.project + '/workdoor/workdoorlist';
        return this.http.get(dataurl, param);
    }

    /**
     * 子表确认
     * @param ids 从表主键集合
     * @param uId 主表主键
     * @param uDate 日期
     */
    queRen(param) {
        const dataurl = environment.project + '/updownRoadd/sureBatch';
        return this.http.post(dataurl, param);
    }


    /**
     * 子表导出
     * @param uSummary  是否是汇总表|0否、1是
     * @param uDwDn  点内还是点外|0天窗点外上道、1天窗点内上道
     * @param uDate  日期|汇总表必须传递主表的日期给此参数，车间表不传
     * @param uId  主表主键|汇总表此参数不传，车间表传
     * @param nWorkshop  部门车间编号|汇总有此筛选项
     * @param uStatus  状态|0已导入、1已确认
     * @param uWorkarea  工区名称
     * @param uStation  车站名称
     */
    expt(param) {
        const dataurl = environment.project + '/updownRoadd/dataExcel';
        return this.http.get(dataurl, param, { responseType: 'blob', observe: 'response' });
    }

}
